package br.com.DAO;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import br.com.model.Cliente;

public class ClienteDAO {
	
	public Connection getConn() throws ClassNotFoundException,SQLException
	{
		Class.forName("com.mysql.jdbc.Driver");
		
		return DriverManager.getConnection("jdbc:mysql://localhost/crud_jsf","root","d0405s");
	}
	
	public List<Cliente> getAll() throws ClassNotFoundException, SQLException
	{
		String SQL = "SELECT * FROM cliente";
		PreparedStatement pstm = getConn().prepareStatement(SQL);
		
		ResultSet rs = pstm.executeQuery();
		
		List<Cliente> lista = new ArrayList<Cliente>();
		
		while(rs.next())
		{
			Cliente c = new Cliente();
			c.setId(rs.getInt("id"));
			c.setNome(rs.getString("nome"));
			c.setEmail(rs.getString("email"));
			c.setIdade(rs.getInt("idade"));
			lista.add(c);
		}
		return lista;
	}
	
	public boolean insert(Cliente c) throws ClassNotFoundException, SQLException
	{
		boolean result = false;
		try
		{
		String SQL = "INSERT INTO cliente (nome,email,idade) VALUES (?,?,?)";
		
		PreparedStatement pstm = getConn().prepareStatement(SQL);
		pstm.setString(1,c.getNome());
		pstm.setString(2,c.getEmail());
		pstm.setInt(3,c.getIdade());
		
		if(pstm.executeUpdate() >0)
		{
			return true;
		}
		else
		{
			return false;
		}
		}
		catch(Exception ex)
		{
			System.out.print("Erro encontrado  " + ex);
		}
		
		return result;
	}
	
	public boolean delete(Cliente c) throws ClassNotFoundException, SQLException
	{
		String SQL = "DELETE FROM cliente WHERE id=?";
		
		PreparedStatement pstm = getConn().prepareStatement(SQL);
		pstm.setInt(1, c.getId());
		
		if(pstm.executeUpdate() >0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	public boolean updade(Cliente c) throws ClassNotFoundException, SQLException
	{
		String SQL = "UPDATE cliente SET nome=?, email=?, idade=? WHERE id=?";
		
		PreparedStatement pstm = getConn().prepareStatement(SQL);
		pstm.setString(1,c.getNome());
		pstm.setString(2,c.getEmail());
		pstm.setInt(3,c.getIdade());
		pstm.setInt(4,c.getId());
		
		if(pstm.executeUpdate() > 0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

}
